package cn.kgm.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 输入还是输出都是相对java文件的（内存）
 */
public class NioFileChanalCopy {

    private final static String nioUrl = "niofile/";

    public static void main(String[] args) throws IOException {
        File input =  new File(nioUrl + "input.txt");
        File output =  new File(nioUrl + "output.txt");

        /**
         * 将数据写到文件中
         */
        FileOutputStream fileOutputStream = new FileOutputStream(output);
        FileChannel fileOutput = fileOutputStream.getChannel();
        /**
         * 将文件中数据写到java程序中
         */
        FileInputStream fileInputStream = new FileInputStream(input);
        FileChannel fileInput = fileInputStream.getChannel();

        ByteBuffer bu =  ByteBuffer.allocate(1);
        for (;;){
            bu.clear();
            int read = fileInput.read(bu);
            if (read == -1){
                break;
            }
            bu.flip();
            fileOutput.write(bu);
        }
        fileInput.close();
        fileOutput.close();
    }
}
